package com.cci.kangdao.service.impl;

import com.cci.kangdao.crmapi.CRMHttpClientUtil;
import com.cci.kangdao.crmapi.CRMServiceConst;
import com.cci.kangdao.dao.CustomerEngineRelDao;
import com.cci.kangdao.service.CSUHealthStatusService;
import com.cci.kangdao.utilTool.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Service("CSUHealthStatusService")
public class CSUHealthStatusServiceImpl implements CSUHealthStatusService {

    @Autowired
    private CustomerEngineRelDao customerEngineRelDao;

    @Override
    public ModelAndView getVehiclesHealthInfos(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse)map.get("response");
        HttpServletRequest request = (HttpServletRequest)map.get("request");

        try {

            /**
             * 查询用户信息
             */
            String userid = request.getHeader("userid");
            userid = AESTool.decryptString(userid);//解密userid
            List<String> userEsns = customerEngineRelDao.getESNListByUserId(Long.parseLong(userid));
            String esnListString = StringUtils.join(userEsns.toArray(), ",");// 以逗号分割

            List<Map<String,Object>> esnModelsList = customerEngineRelDao.getESNModelListByUserId(Long.parseLong(userid));
            Map<String,Object> equipmentNoMap = new HashedMap();
            if (esnModelsList == null || esnModelsList.size() == 0){

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("status", 0);//自定义http code
                jsonObject.put("msg", "暂无绑定车辆信息");
                jsonObject.put("data",new JSONObject());
                ParameterTool.writeResponse(response, jsonObject.toString());
                return null;
            }

            /**
             * 将esn和equipmentNO放入map，esn为key，equipmentNO为value
             */
            for (int i = 0; i < esnModelsList.size(); i++) {
                Map<String,Object> esnModelMap = esnModelsList.get(i);
                equipmentNoMap.put(esnModelMap.get("ESN").toString(),esnModelMap.get("equipmentNo"));
            }

            String wwid = PropertiesUtil.getProperties("projectconfig.properties", "csu.wwid").trim();
            String token = PropertiesUtil.getProperties("projectconfig.properties", "csu.token").trim();

            /**
             * 请求头参数
             */
            Map<String,Object> headerMap = new HashedMap();
            headerMap.put("wwid",wwid);
            headerMap.put("token",token);

            String serverUrl = PropertiesUtil.getProperties("projectconfig.properties", "csu.upgrade.host").trim();
            serverUrl = serverUrl + CRMServiceConst.CSU_GET_VEHICLESHEALTHINFO;

            /**
             * get 请求参数
             */
            Map<String,Object> requestParamMap = new HashedMap();
            requestParamMap.put("esnList",esnListString);

            /**
             * 发起网络请求
             */

            JSONObject responseObject = CRMHttpClientUtil.httpGETRequest(serverUrl,null,requestParamMap);
            JSONObject responseData = responseObject.getJSONObject("data");
            if (responseData != null && !responseData.isEmpty()){ // data值为空
                responseData.put("vehicleNums",userEsns.size());

                JSONArray vehicleHistoriesArr = responseData.getJSONArray("vehicles");
                if (vehicleHistoriesArr != null && !vehicleHistoriesArr.isEmpty()){
                    /**
                     * 给发动机基础信息添加设备号字段
                     */
                    for (int j = 0; j < vehicleHistoriesArr.size(); j++) {
                        JSONObject vehicleJson = (JSONObject) vehicleHistoriesArr.get(j);
                        vehicleJson.put("equipmentNo",equipmentNoMap.get(vehicleJson.get("ESN").toString()));
                    }
                }

            }else {// data值为空，使用新建json data返回注册车辆数

                JSONObject vehicleNumsJson = new JSONObject();
                vehicleNumsJson.put("vehicleNums",0);
                responseObject.put("data",vehicleNumsJson);
            }
            //返回客户
            ParameterTool.writeResponse(response, responseObject.toString());

        }catch (Exception ex){

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", -99);//自定义http code
            jsonObject.put("msg", ex.getMessage());
            ParameterTool.writeResponse(response, jsonObject.toString());

        }

        return null;
    }

}
